import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import HomeView from '../views/HomeView.vue'
import LoginView from '../views/LoginView.vue'
import type { RouteRecordRaw } from 'vue-router'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/home',
      name: 'home',
      component: HomeView,
      meta: { requiresAuth: true },
      children: [
        {
          path: 'process-classification',
          name: 'process-classification',
          component: () => import('../views/ProcessClassification.vue'),
          meta: { requiresAuth: true }
        },
        {
          path: 'process-management',
          name: 'process-management',
          component: () => import('../views/ProcessManagement.vue'),
          meta: { requiresAuth: true }
        },
        {
          path: 'process-flow',
          name: 'process-flow',
          component: () => import('../views/ProcessFlow.vue'),
          meta: { requiresAuth: true }
        }
      ]
    },

    {
      path: '/',
      name: 'login',
      component: LoginView,
      meta: { requiresAuth: false }
    },
    {
      path: '/about',
      name: 'about',
      component: () => import('../views/AboutView.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/weather-alert',
      name: 'weather-alert',
      component: () => import('../views/WeatherAlert.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/production-plan',
      name: 'ProductionPlan',
      component: () => import('@/views/ProductionPlanView.vue')
    },
    {
      path: '/create-production-plan',
      name: 'CreateProductionPlan',
      component: () => import('@/views/CreateProductionPlanView.vue')
    },
    {
      path: '/production-plan/:id',
      name: 'ProductionPlanDetail',
      component: () => import('@/views/ProductionPlanDetailView.vue')
    },
    {
      path: '/BOMView',
      name: 'BOMView',
      component: () => import('../views/BOMView.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/AddBOMView',
      name: 'AddBOMView',
      component: () => import('../views/AddBOMView.vue'),
      meta: { requiresAuth: true }
    },
    // 详情改由主布局标签页承载，此处无需独立路由
  ],
})

router.beforeEach((to, from, next) => {
  const authStore = useAuthStore()
  
  if (to.meta.requiresAuth && !authStore.isAuthenticated) {
    next('/login')
  } else if (to.path === '/login' && authStore.isAuthenticated) {
    next('/home')
  } else {
    next()
  }
})

export default router
